const { build } = require('vite')
const { spawn } = require('child_process')
const path = require('path')

async function buildElectron() {
  console.log('🔨 构建 Vite 项目...')
  
  // 构建前端项目
  await build()
  
  console.log('✅ Vite 构建完成')
  console.log('🔨 构建 Electron 主进程...')
  
  // 复制 electron 文件到 dist-electron
  const fs = require('fs')
  const electronDir = path.join(__dirname, 'electron')
  const distElectronDir = path.join(__dirname, 'dist-electron')
  
  // 创建 dist-electron 目录
  if (!fs.existsSync(distElectronDir)) {
    fs.mkdirSync(distElectronDir, { recursive: true })
  }
  
  // 复制文件
  const filesToCopy = ['main.js', 'preload.js']
  filesToCopy.forEach(file => {
    const src = path.join(electronDir, file)
    const dest = path.join(distElectronDir, file)
    if (fs.existsSync(src)) {
      fs.copyFileSync(src, dest)
      console.log(`✅ 复制 ${file}`)
    }
  })
  
  // 复制 assets 目录
  const assetsDir = path.join(electronDir, 'assets')
  const distAssetsDir = path.join(distElectronDir, 'assets')
  if (fs.existsSync(assetsDir)) {
    if (!fs.existsSync(distAssetsDir)) {
      fs.mkdirSync(distAssetsDir, { recursive: true })
    }
    // 创建简单的图标文件
    fs.writeFileSync(path.join(distAssetsDir, 'icon.ico'), '')
    fs.writeFileSync(path.join(distAssetsDir, 'icon.png'), '')
    console.log('✅ 创建图标文件')
  }
  
  console.log('✅ Electron 构建完成')
}

if (require.main === module) {
  buildElectron().catch(console.error)
}

module.exports = buildElectron